import 'dart:ui';

import 'package:asperm/tools/storage.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:intl/intl.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

import '../generated/l10n.dart';
import '../main.dart';
import 'current_locale.dart';
import 'dart:io';


// 邮箱正则
const String regexEmail =
    "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}\$";

// 检查是否是邮箱格式
bool isEmail(String input) {
  if (input == '' || input.isEmpty) return false;
  return RegExp(regexEmail).hasMatch(input);
}


showLoading(String? string){
  EasyLoading.instance
    ..displayDuration = const Duration(milliseconds: 3000)
    ..indicatorType = EasyLoadingIndicatorType.threeBounce
    ..loadingStyle = EasyLoadingStyle.custom
    ..indicatorSize = 30.0
    ..radius = 10.0
  // ..progressColor = Colors.yellow
    ..backgroundColor = Color(0xFF777777).withOpacity(0.8)
    ..indicatorColor = Colors.white
    ..textColor = Colors.white
  // ..maskColor = Colors.blue.withOpacity(0.5)
    ..userInteractions = false
  // ..boxShadow = [] //透明度
    ..dismissOnTap = false;
  BuildContext context = navigatorKey.currentState!.overlay!.context;
  EasyLoading.show(status:string ?? S.of(context).loading);
}

showToast(String msg){
  EasyLoading.showToast(msg,duration: Duration(milliseconds: 3000));
}

hideLoading(){
  EasyLoading.dismiss();
}

///获取服务器 国家 参数
getCurrentLanguageCode(){
  String languageCode = SpUtil.preferences.getString('languageCode') ?? 'en';
  return languageCode;
}

//获取当前时间戳
getCurrentTimestamp(){
  DateTime currentTime = DateTime.now();
  int timestamp = currentTime.millisecondsSinceEpoch ~/ 1000;
  return timestamp;
}

//时间戳转 格式化后的时间
String getDateStringFromTimestamp(int timestamp) {

  if(timestamp == 0){
    return '';
  }

  // 首先将时间戳转换为UTC时间的DateTime对象,服务器时间秒级改为毫秒级
  DateTime utcDateTime =
  DateTime.fromMillisecondsSinceEpoch(timestamp * 1000, isUtc: true);
  // 然后将UTC时间转换为本地时区的时间
  DateTime localDateTime = utcDateTime.toLocal();
  // 使用DateFormat格式化日期和时间
  String formattedDate = DateFormat('MM/dd/yyyy,HH:mm').format(localDateTime);

  List<String> DateList = formattedDate.split(',');

  String dateString = dateToEnDate(DateList.first);
  // 返回格式化后的日期字符串
  //根据语言显示不同的格式
  Locale loale = LanguageProvider().getCurrentLanguage();
  print('===========loale.languageCode:${loale.languageCode}');
  print('===========DateList:${DateList}');
  print('===========dateString:${dateString}');
  print('===========DateList.last:${DateList.last}');
  print('===========DateList.first:${DateList.first}');

  if(loale.languageCode == 'zh'){
    return formattedDate;
  }else{
    return '${dateString},${DateList.last}';
  }

}

//转英文时间
//2024-11-04 ---> 4Nov,2024
//1-12月缩写为：Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
dateToEnDate(String date){
  var monthList = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  String result = '';

  if(date.contains('-')){
    var dateList = date.split('-');
    int month = (int.tryParse(dateList[1]) ?? 1) - 1;
    if(dateList.length == 3){
      int day = int.tryParse(dateList.last) ?? 1;
      result = '${day}${monthList[month]},${dateList.first}';
    }else{
      result = '${monthList[month]},${dateList.first}';
    }
  }else if(date.contains('/')){
    var dateList = date.split('/');
    int month = (int.tryParse(dateList[0]) ?? 1) - 1;
    int day = int.tryParse(dateList[1]) ?? 1;
    print('-----------day:${day}');
    result = '${monthList[month]}${day},${dateList.last}';
  }
  return result;
}

getAppVersionInfo() async {
  PackageInfo packageInfo = await PackageInfo.fromPlatform();
  String version = packageInfo.version;
  String appVersion = '';

  // String appName = packageInfo.appName;
  // String packageName = packageInfo.packageName;
  String buildNumber = packageInfo.buildNumber;
  appVersion = version;

  return appVersion;
}

Future<void> goToLaunchUrl(String urlString) async {
  Uri _url = Uri.parse(urlString);
  if (!await launchUrl(_url)) {
    throw Exception('Could not launch $_url');
  }
}


JumpToAppStore(){
  if(Platform.isIOS){
    // String appUrl ="https://apps.apple.com/app/id6498888302";
    String appUrl ="itms-apps://itunes.apple.com/cn/app/id6498888302?mt=8";
    goToLaunchUrl(appUrl);//到APP store 官网下载
  }else{
    String appUrl = "https://play.google.com/store/apps/details?id=com.anstandor.cordx";
    goToLaunchUrl(appUrl);//到Google Play 官网下载
  }

}

// 隐藏键盘
hideKeyboard(BuildContext context) {
  FocusScopeNode currentFocus = FocusScope.of(context);
  if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
    FocusManager.instance.primaryFocus!.unfocus();
  }
}

goLogin(BuildContext context) {
  // 跳转到一个新的页面
  Navigator.pushNamedAndRemoveUntil(context, '/login', (route) => false);
}

//申请存本地相册权限
Future<bool> getSavePhotoPermission() async {
  print('------getSavePhotoPermission');
  if (Platform.isIOS) {
    var status = await Permission.photos.status;

    if (status.isDenied) {
      print('------isDenied');


      final newStatus = await Permission.photos.request();
      return newStatus.isGranted;
      // saveImage(globalKey);
    }
    return status.isGranted;
  } else {

    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
    double versionString = double.parse(androidInfo.version.release); // Android SDK 版本

    if(versionString > 13){
      var status = await Permission.photos.status;
      if (status.isDenied) {
        // Map<Permission, PermissionStatus> statuses = await [
        //   Permission.storage,
        // ].request();
        status = await Permission.photos.request();
      }
      print('------------status:${status}');
      return status.isGranted;
    }else{
      //android 13及以后 被弃用
      var status = await Permission.storage.status;
      if (status.isDenied) {
        // Map<Permission, PermissionStatus> statuses = await [
        //   Permission.storage,
        // ].request();
        status = await Permission.storage.request();
      }
      print('------------status:${status}');
      return status.isGranted;
    }


  }
}

